<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统中的所有用户账号</p>
    </div>
    
    <el-card class="filter-card">
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名/邮箱"
          clearable
          class="filter-item"
          @clear="searchUsers"
        >
          <template #append>
            <el-button @click="searchUsers">
              <i class="el-icon-search"></i>
            </el-button>
          </template>
        </el-input>
        
        <div class="action-buttons">
          <el-button type="primary" @click="showBatchRegisterDialog">
            批量注册
          </el-button>
          <el-button type="success" @click="handleBatchAction('roles')">
            批量设置角色
          </el-button>
          <el-button type="warning" @click="handleBatchAction('ban')">
            批量封禁
          </el-button>
          <el-button type="info" @click="handleBatchAction('unban')">
            批量解封
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 用户列表 -->
    <el-card class="user-table-card">
      <el-table
        ref="multipleTable"
        :data="displayedUsers"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        
        <el-table-column label="用户名" width="120">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="30" :src="getAvatarUrl(scope.row.avatarUrl)"></el-avatar>
              <span>{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="email" label="邮箱"></el-table-column>
        
        <el-table-column prop="fullName" label="姓名" width="100">
          <template #default="scope">
            {{ scope.row.fullName || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="phoneNumber" label="手机号" width="120">
          <template #default="scope">
            {{ scope.row.phoneNumber || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="examNumber" label="学号" width="120">
          <template #default="scope">
            {{ scope.row.examNumber || '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'danger'">
              {{ scope.row.enabled ? '正常' : '封禁' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="角色" width="180">
          <template #default="scope">
            <template v-if="scope.row.roles && scope.row.roles.length > 0">
              <el-tag
                v-for="role in scope.row.roles"
                :key="role"
                size="small"
                :type="getRoleType(role)"
                class="role-tag"
              >
                {{ formatRole(role) }}
              </el-tag>
            </template>
            <el-text v-else type="info" size="small">未设定角色</el-text>
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleSetRole(scope.row)"
            >
              角色
            </el-button>
            <el-button
              size="small"
              :type="scope.row.enabled ? 'danger' : 'info'"
              @click="handleBanUser(scope.row)"
            >
              {{ scope.row.enabled ? '封禁' : '解封' }}
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleResetPassword(scope.row)"
            >
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      v-model="editDialogVisible"
      width="500px"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="fullName">
          <el-input v-model="editForm.fullName"></el-input>
        </el-form-item>
        
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="editForm.phoneNumber"></el-input>
        </el-form-item>
        
        <el-form-item label="学号" prop="examNumber">
          <el-input v-model="editForm.examNumber"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 设置角色对话框 -->
    <el-dialog
      title="设置用户角色"
      v-model="roleDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-form-item label="用户">
          <span>{{ currentUser?.username }}</span>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-checkbox-group v-model="selectedRoles">
            <el-checkbox value="ROLE_ADMIN">管理员</el-checkbox>
            <el-checkbox value="ROLE_TEACHER">教师</el-checkbox>
            <el-checkbox value="ROLE_USER">普通用户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRoles" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 批量角色设置对话框 -->
    <el-dialog
      title="批量设置角色"
      v-model="batchRoleDialogVisible"
      width="400px"
    >
      <el-form label-width="100px">
        <el-form-item label="已选用户">
          <span>{{ selectedUsers.length }}个用户</span>
        </el-form-item>
        
        <el-form-item label="设置角色">
          <el-checkbox-group v-model="batchSelectedRoles">
            <el-checkbox value="ROLE_ADMIN">管理员</el-checkbox>
            <el-checkbox value="ROLE_TEACHER">教师</el-checkbox>
            <el-checkbox value="ROLE_USER">普通用户</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchRoles" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 批量注册对话框 -->
    <el-dialog
      title="批量注册用户"
      v-model="batchRegisterDialogVisible"
      width="600px"
    >
      <el-form
        ref="batchRegisterFormRef"
        :model="batchRegisterForm"
        label-width="100px"
      >
        <el-form-item label="用户数据">
          <el-input
            type="textarea"
            v-model="batchRegisterForm.usersData"
            :rows="10"
            placeholder="请输入用户数据，每行一个用户，格式：用户名,密码,邮箱,学号(可选),姓名(可选),手机号(可选)"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="默认角色">
          <el-checkbox-group v-model="batchRegisterForm.roles">
            <el-checkbox value="ROLE_USER">普通用户</el-checkbox>
            <el-checkbox value="ROLE_TEACHER">教师</el-checkbox>
            <el-checkbox value="ROLE_ADMIN">管理员</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="batchRegisterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchRegister" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import config from '../../config'

export default {
  name: 'UserManagement',
  setup() {
    const store = useStore()
    const multipleTable = ref(null)
    const batchRegisterFormRef = ref(null)
    
    // 列表数据
    const users = ref([])
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const searchQuery = ref('')
    
    // 选中的用户
    const selectedUsers = ref([])
    
    // 当前编辑的用户
    const currentUser = ref(null)
    
    // 对话框控制
    const editDialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const batchRoleDialogVisible = ref(false)
    const batchRegisterDialogVisible = ref(false)
    const submitLoading = ref(false)
    
    // 表单数据
    const editForm = reactive({
      id: null,
      username: '',
      email: '',
      fullName: '',
      phoneNumber: '',
      examNumber: ''
    })
    
    // 角色选择
    const selectedRoles = ref([])
    const batchSelectedRoles = ref(['ROLE_USER'])
    
    // 批量注册表单
    const batchRegisterForm = reactive({
      usersData: '',
      roles: ['ROLE_USER']
    })
    
    // 验证规则
    const validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else {
        const phoneReg = /^1[3-9]\d{9}$/
        if (!phoneReg.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
    }
    
    const editRules = {
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phoneNumber: [
        { validator: validatePhone, trigger: 'blur' }
      ]
    }
    
    // 获取完整头像URL
    const getAvatarUrl = (avatarUrl) => {
      return config.getFullResourceUrl(avatarUrl);
    };
    
    // 获取用户列表
    const fetchUsers = async (refresh = false) => {
      // 如果数据已加载且不是强制刷新，则直接使用已有数据进行前端分页
      if (users.value.length > 0 && !refresh) {
        return;
      }
      
      loading.value = true
      
      try {
        const response = await axios.get('/api/users', {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          const data = response.data.data
          
          // 确保每个用户都有roles字段
          const processedData = data.map(user => ({
            ...user,
            roles: user.roles || []
          }))
          
          // 如果有搜索查询，进行前端筛选
          if (searchQuery.value) {
            const query = searchQuery.value.toLowerCase()
            users.value = processedData.filter(user => 
              user.username.toLowerCase().includes(query) || 
              (user.email && user.email.toLowerCase().includes(query))
            )
          } else {
            users.value = processedData
          }
          
          total.value = users.value.length
        } else {
          ElMessage.error(response.data.message || '获取用户列表失败')
        }
      } catch (error) {
        ElMessage.error('获取用户数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 表格选择变化
    const handleSelectionChange = (val) => {
      selectedUsers.value = val
    }
    
    // 分页相关
    const handleSizeChange = (size) => {
      pageSize.value = size
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
    }
    
    // 搜索用户
    const searchUsers = () => {
      if (users.value.length === 0) {
        fetchUsers(true);
        return;
      }
      
      // 前端搜索逻辑
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        const allUsers = [...users.value]; // 创建一个副本
        users.value = allUsers.filter(user => 
          user.username.toLowerCase().includes(query) || 
          (user.email && user.email.toLowerCase().includes(query))
        );
      } else {
        fetchUsers(true); // 如果搜索条件为空，重新获取所有数据
      }
      
      // 重置分页
      currentPage.value = 1;
    }
    
    // 计算当前页显示的用户
    const displayedUsers = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return users.value.slice(start, end);
    });
    
    // 编辑用户
    const handleEdit = (user) => {
      currentUser.value = user
      editForm.id = user.id
      editForm.username = user.username
      editForm.email = user.email || ''
      editForm.fullName = user.fullName || ''
      editForm.phoneNumber = user.phoneNumber || ''
      editForm.examNumber = user.examNumber || ''
      
      editDialogVisible.value = true
    }
    
    // 编辑用户成功后刷新用户数据
    const refreshUserData = (userId, newData) => {
      const index = users.value.findIndex(user => user.id === userId);
      if (index !== -1) {
        users.value[index] = { ...users.value[index], ...newData };
      }
    };
    
    // 提交编辑表单
    const submitEditForm = async () => {
      submitLoading.value = true
      
      try {
        const response = await axios.put(`/api/users/${editForm.id}`, {
          email: editForm.email,
          fullName: editForm.fullName,
          phoneNumber: editForm.phoneNumber,
          examNumber: editForm.examNumber
        }, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('用户信息更新成功')
          editDialogVisible.value = false
          
          // 更新本地用户数据
          refreshUserData(editForm.id, {
            email: editForm.email,
            fullName: editForm.fullName,
            phoneNumber: editForm.phoneNumber,
            examNumber: editForm.examNumber
          });
        } else {
          ElMessage.error(response.data.message || '更新失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 角色设置
    const handleSetRole = (user) => {
      currentUser.value = user
      selectedRoles.value = user.roles || []
      roleDialogVisible.value = true
    }
    
    // 提交角色设置
    const submitRoles = async () => {
      submitLoading.value = true
      
      try {
        const response = await axios.put(`/api/users/${currentUser.value.id}/roles`, {
          roles: selectedRoles.value
        }, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('用户角色更新成功')
          roleDialogVisible.value = false
          
          // 更新本地用户数据
          refreshUserData(currentUser.value.id, {
            roles: selectedRoles.value
          });
        } else {
          ElMessage.error(response.data.message || '更新失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 封禁/解封用户
    const handleBanUser = async (user) => {
      const action = user.enabled ? '封禁' : '解封'
      const endpoint = user.enabled ? 'ban' : 'unban'
      
      try {
        const response = await axios.put(`/api/users/${user.id}/${endpoint}`, null, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success(`用户${action}成功`)
          
          // 更新本地用户数据
          refreshUserData(user.id, {
            enabled: !user.enabled
          });
        } else {
          ElMessage.error(response.data.message || `${action}失败`)
        }
      } catch (error) {
        ElMessage.error(`${action}失败，请稍后重试`)
      }
    }
    
    // 批量操作
    const handleBatchAction = (action) => {
      if (selectedUsers.value.length === 0) {
        ElMessage.warning('请先选择用户')
        return
      }
      
      if (action === 'roles') {
        batchRoleDialogVisible.value = true
      } else if (action === 'ban') {
        ElMessageBox.confirm('确定要封禁选中的用户吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchBanUsers(true)
        }).catch(() => {})
      } else if (action === 'unban') {
        ElMessageBox.confirm('确定要解封选中的用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        }).then(() => {
          batchBanUsers(false)
        }).catch(() => {})
      }
    }
    
    // 批量封禁/解封用户
    const batchBanUsers = async (isBan) => {
      const userIds = selectedUsers.value.map(user => user.id)
      const endpoint = isBan ? 'batch-ban' : 'batch-unban'
      
      try {
        // 直接发送userIds数组作为请求体，不包装在对象中
        const response = await axios.put(`/api/users/${endpoint}`, userIds, {
          headers: { 
            Authorization: `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.data.success) {
          ElMessage.success(response.data.message)
          
          // 更新本地用户数据
          selectedUsers.value.forEach(user => {
            refreshUserData(user.id, { enabled: !isBan });
          });
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('批量操作错误:', error);
        ElMessage.error(`操作失败: ${error.response?.data?.message || '请稍后重试'}`)
      }
    }
    
    // 提交批量角色设置
    const submitBatchRoles = async () => {
      if (batchSelectedRoles.value.length === 0) {
        ElMessage.warning('请至少选择一个角色')
        return
      }
      
      submitLoading.value = true
      const userIds = selectedUsers.value.map(user => user.id)
      
      try {
        // 修正请求体格式
        const response = await axios.put('/api/users/batch-roles', {
          userIds: userIds, // 显式指定为数组类型
          roles: batchSelectedRoles.value
        }, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('批量更新用户角色成功')
          batchRoleDialogVisible.value = false
          
          // 更新本地用户数据
          selectedUsers.value.forEach(user => {
            refreshUserData(user.id, { roles: batchSelectedRoles.value });
          });
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        console.error('批量角色设置错误:', error);
        ElMessage.error(`操作失败: ${error.response?.data?.message || '请稍后重试'}`)
      } finally {
        submitLoading.value = false
      }
    }
    
    // 显示批量注册对话框
    const showBatchRegisterDialog = () => {
      batchRegisterForm.usersData = ''
      batchRegisterForm.roles = ['ROLE_USER']
      batchRegisterDialogVisible.value = true
    }
    
    // 提交批量注册
    const submitBatchRegister = async () => {
      if (!batchRegisterForm.usersData.trim()) {
        ElMessage.warning('请输入用户数据')
        return
      }
      
      submitLoading.value = true
      
      try {
        // 解析用户数据
        const lines = batchRegisterForm.usersData.trim().split('\n')
        const users = lines.map(line => {
          const [username, password, email, examNumber, fullName, phoneNumber] = line.split(',').map(item => item.trim())
          return {
            username,
            password,
            email,
            examNumber,
            fullName,
            phoneNumber
          }
        })
        
        // 调用API
        const response = await axios.post('/api/users/batch-register', {
          users,
          roles: batchRegisterForm.roles
        }, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('批量注册用户成功')
          batchRegisterDialogVisible.value = false
          // 这里需要重新获取用户列表，因为新增了用户
          fetchUsers(true)
        } else {
          ElMessage.error(response.data.message || '操作失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 生成密码重置令牌
    const handleResetPassword = async (user) => {
      try {
        const response = await axios.post('/api/password/generate-reset-token', {
          username: user.username
        }, {
          headers: { Authorization: `Bearer ${store.state.token}` }
        })
        
        if (response.data.success) {
          ElMessage.success(`密码重置令牌生成成功: ${response.data.data.token}`)
        } else {
          ElMessage.error(response.data.message || '生成令牌失败')
        }
      } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
      }
    }
    
    // 格式化角色名称
    const formatRole = (role) => {
      const roleMap = {
        'ROLE_ADMIN': '管理员',
        'ROLE_USER': '普通用户',
        'ROLE_TEACHER': '教师'
      }
      return roleMap[role] || role
    }
    
    // 获取角色标签类型
    const getRoleType = (role) => {
      const typeMap = {
        'ROLE_ADMIN': 'danger',
        'ROLE_USER': 'primary',
        'ROLE_TEACHER': 'success'
      }
      return typeMap[role] || 'info'
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      
      const date = new Date(dateString)
      return date.toLocaleString()
    }
    
    onMounted(() => {
      fetchUsers()
    })
    
    return {
      multipleTable,
      users,
      loading,
      total,
      currentPage,
      pageSize,
      searchQuery,
      selectedUsers,
      currentUser,
      editDialogVisible,
      roleDialogVisible,
      batchRoleDialogVisible,
      batchRegisterDialogVisible,
      submitLoading,
      editForm,
      selectedRoles,
      batchSelectedRoles,
      batchRegisterForm,
      batchRegisterFormRef,
      editRules,
      
      fetchUsers,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleEdit,
      submitEditForm,
      handleSetRole,
      submitRoles,
      handleBanUser,
      handleBatchAction,
      submitBatchRoles,
      showBatchRegisterDialog,
      submitBatchRegister,
      handleResetPassword,
      formatRole,
      getRoleType,
      formatDate,
      getAvatarUrl,
      displayedUsers,
      searchUsers,
      refreshUserData
    }
  }
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 5px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.user-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info span {
  margin-left: 8px;
}

.role-tag {
  margin-right: 5px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-item {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .action-buttons {
    width: 100%;
  }
}
</style> 